package com.cq.smartelebicycle.view;


import com.cq.smartelebicycle.R;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.widget.ImageView;

public class NumberImageView extends ImageView {

	private static final int DISPLAY_SCALE = 10;
	private Paint paint;
	private int displayHeight;
	private String numberStr = "0";
	private int textSize = 100;

	public NumberImageView(Context context, AttributeSet attrs) {
		super(context, attrs);
		// TODO Auto-generated constructor stub
		DisplayMetrics mDisplayMetrics = new DisplayMetrics();
		((Activity) context).getWindowManager().getDefaultDisplay()
				.getMetrics(mDisplayMetrics);
		displayHeight = mDisplayMetrics.heightPixels;
		TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.NumberImageView);
		int color = a.getColor(R.styleable.NumberImageView_textcolor, Color.RED);
		a.recycle();
		paint = new Paint();
		paint.setTextAlign(Paint.Align.CENTER);
		paint.setColor(color);
		paint.setTextSize(textSize);
		paint.setAntiAlias(true);
	
	}

	@Override
	protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
		// TODO Auto-generated method stub
		super.onMeasure(widthMeasureSpec, heightMeasureSpec);
		int height = displayHeight / DISPLAY_SCALE;
		int width = (int) ((float) getBackground().getIntrinsicWidth()
				/ (float) getBackground().getIntrinsicHeight() * height);
		setMeasuredDimension(width, height);

	}

	public void setNumber(int number) {
		numberStr = String.valueOf(number);
		invalidate();
	}

	@SuppressLint("DrawAllocation")
	@Override
	protected void onDraw(Canvas canvas) {
		// TODO Auto-generated method stub
		super.onDraw(canvas);
		int w = getWidth();
		int h = getHeight();
		Rect textBounds = new Rect();
		paint.getTextBounds(numberStr, 0, numberStr.length(), textBounds);
		while (textBounds.bottom - textBounds.top > getHeight() * 3 / 5) {
			textSize -= 2;
			paint.setTextSize(textSize);
			paint.getTextBounds(numberStr, 0, numberStr.length(), textBounds);
		}
		canvas.drawText(numberStr, w / 2, h / 2
				+ (textBounds.bottom - textBounds.top) / 2, paint);
	}
}
